package com.lin.videospringboot.controller;

import com.lin.videospringboot.Utils.ParseJson;
import com.lin.videospringboot.been.Post;
import com.lin.videospringboot.service.PostServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/video/post")
public class PostController {
    @Autowired
    PostServiceImpl postService;

    @RequestMapping("/addPost")
    @ResponseBody
    public Post addPost(@RequestBody String s) {
        Map<String,Object> mp = ParseJson.parseJson(s);
        Post post = null;
        try {
            post = Post.builder().content((String) mp.get("content")).userId((int) mp.get("userId"))
                    .time((long)mp.get("time")).likes(0).dislikes(0).build();
            postService.addPost(post);
        }catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return post;
    }

    @RequestMapping("/getList")
    @ResponseBody
    public Map<String,Object> getAllPost(@RequestBody String s) {
        Map<String,Object> mp = ParseJson.parseJson(s);
        int start = (int)mp.get("start");
        int len = (int)mp.get("len");
        System.out.println(start);
        System.out.println(len);

        List<Map<String,Object>> list =  postService.pageQueryWithUserInfo(start,len).getRecords();
        int totNum = postService.queryNum();
        Map<String,Object> res = new HashMap<>();
        res.put("list",list);
        res.put("totNum",totNum);
        return res;
    }


//    TODO: 评论likes值改变
    @RequestMapping("/updatePostLikes")
    @ResponseBody
    public int updatePostLikes(@RequestBody String s) {
        try {
            Map<String,Object> mp = ParseJson.parseJson(s);
            int postId = (int)mp.get("postId");
            int likes = (int)mp.get("likes");
            Post post = postService.getPostById(postId);
            post.setLikes(likes);
            return postService.updatePost(post);
        }catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

//    TODO: 评论dislikes值改变
    @RequestMapping("/updatePostDislikes")
    @ResponseBody
    public int updatePostDislikes(@RequestBody String s) {
        try {
            Map<String,Object> mp = ParseJson.parseJson(s);
            int postId = (int)mp.get("postId");
            int dislikes = (int)mp.get("dislikes");
            Post post = postService.getPostById(postId);
            post.setDislikes(dislikes);
            return postService.updatePost(post);
        }catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

}
